package com.demo.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * CustomAuthenticationProvider
 *
 * @author chenyang
 * @date 2020/10/9
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        System.out.println(authentication);
        String encoder = passwordEncoder.encode("111");
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("admin"));
        if (passwordEncoder.matches((String)authentication.getCredentials(), encoder)) {
            return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), encoder, list);
        }
        throw  new BadCredentialsException("用户名或密码错误");
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
